//将 x 减到 0 的最小操作数
//https://leetcode.cn/problems/minimum-operations-to-reduce-x-to-zero/description/
public class MinOperations {
    /*
    思路正难则反，转化位：数组左右两侧的数相加为x, 那么数组中间的数就为数组元素和-x,利用滑动窗口来找到这个target，寻找子数组的最大长度
    */
    public int minOperations(int[] nums, int x) {
        int target = 0;
        for(int num : nums){
            target += num;
        }
        target -= x;
        if(target < 0){  //处理细节
            return -1;
        }
        int n = nums.length;
        int left = 0, right = 0;
        int sum = 0, ans = n+1;
        while(right < n){
            sum += nums[right];
            while(left < n && sum > target) {
                sum -= nums[left];
                left++;
            }

            if(sum == target){ //更新结果
                ans = Math.min(ans, n - (right -left + 1) );
            }
            right++;
        }

        return ans == n+1 ? -1 : ans;
    }
}
